const {createUserAndRole, getUserAndRoleList, updateUserAndRole,getUserAndRoleOne} = require('../service/userAndRole')
const {SuccessModel, ErrorModel} = require('../model/ResModel')
const {addRoleFailInfo} = require('../model/ErrorInfo')
const {flatData} = require('../utils/flatData')

const postUserAndRole = async ({uid, rid}) => {
  const userAndRole = await createUserAndRole({uid, rid})

  try {
    return new SuccessModel(userAndRole)
  } catch (e) {
    return new ErrorModel(addRoleFailInfo)
  }
}

const getUserAndRole = async ({userName = '', roleName = '', pageIndex = 0, pageSize = 10}) => {
  const result = await getUserAndRoleList({userName, roleName, pageIndex, pageSize})
  result.data = flatData(result.data)

  return new SuccessModel(result)
}

const patchUserAndRole = async ({rid, id}) => {
  const result = await updateUserAndRole({rid, id})
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

const getUserAndRoleById = async (id) => {
  let result = await getUserAndRoleOne(+id)
  result = flatData(result)
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

module.exports = {
  postUserAndRole,
  getUserAndRole,
  patchUserAndRole,
  getUserAndRoleById
}
